package com.mayn.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertiesUtil {

	private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class);

	private static Properties staticProperties = new Properties();

	public static String getConfig(String key) {
		String ret = "";
		InputStream is = null;
		if (staticProperties.isEmpty()) {
			try {
				String startPath = URLDecoder.decode(PropertiesUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "utf-8");
				if (startPath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
					// 截取路径中的jar包名
					startPath = startPath.substring(0, startPath.lastIndexOf("/") + 1);
				}
				// LOG.info("start path : " + startPath);
				String configFilePath = startPath + "" + "config.properties";
				if (FileUtil.exist(configFilePath)) {
					is = new BufferedInputStream(new FileInputStream(configFilePath));
					staticProperties.load(is);

				} else {

				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
				e.printStackTrace();
			} finally {
				try {
					if (is != null)
						is.close();
				} catch (IOException e) {
					LOG.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
		if (!staticProperties.isEmpty()) {
			ret = staticProperties.getProperty(key).trim().toString();
		}
		return ret;
	}

}
